package com.imdroid.lite.net.udp;

public class IntegerTransfer {

	/**
	 * ���ֽ������ָ��λ�����2��byteת���ɶ�����
	 * @param rawData
	 * 	ԭʼ����
	 * @param startIdx
	 *  ��ʼ�±�
	 * @return
	 * ����������
	 */
	public static short byteToShort(byte[] rawData, int startIdx) {
		return (short)(((rawData[startIdx] & 0xFF) << 8)
				| (rawData[startIdx + 1] & 0xFF));
	}

	/**
	 * �Ѷ�����ת�����ֽ�����
	 * @param data
	 * 	������
	 * @return
	 * 	����Ϊ2�Ĵ��������������ֵ������
	 */
	public static byte[] shortToByte(short data) {
		byte[] res = new byte[2];
		res[0] = (byte) ((data >>> 8) & 0xFF);
		res[1] = (byte) (data & 0xFF);
		return res;
	}
	
	/**
	 * ���ֽ������ָ��λ�����4��byteת��������
	 * @param rawData
	 * 	ԭʼ����
	 * @param startIdx
	 *  ��ʼ�±�
	 * @return
	 * 	����������
	 */
	public static int byteToInt(byte[] rawData, int startIdx) {
		return (rawData[startIdx] << 24)
				| ((rawData[startIdx + 1] & 0xFF) << 16)
				| ((rawData[startIdx + 2] & 0xFF) << 8)
				| (rawData[startIdx + 3] & 0xFF);
	}


	/**
	 * ������ת�����ֽ�����
	 * @param data
	 * 	����
	 * @return
	 * 	����Ϊ4�Ĵ�������������ֵ������
	 */
	public static byte[] intToByte(int data) {
		byte[] res = new byte[4];
		res[0] = (byte) ((data >>> 24) & 0xFF);
		res[1] = (byte) ((data >>> 16) & 0xFF);
		res[2] = (byte) ((data >>> 8) & 0xFF);
		res[3] = (byte) (data & 0xFF);
		return res;
	}

	/**
	 * ���ֽ������ָ��λ�����8��byteת���ɳ�����
	 * @param rawData
	 * 	ԭʼ����
	 * @param startIdx
	 *  ��ʼ�±�
	 * @return
	 * 	����������
	 */
	public static long byteToLong(byte[] rawData, int startIdx) {
		return ((long)rawData[startIdx] << 56)
				| ((long)(rawData[startIdx + 1] & 0xFF) << 48)
				| ((long)(rawData[startIdx + 2] & 0xFF) << 40)
				| ((long)(rawData[startIdx + 3] & 0xFF) << 32)
				| ((long)(rawData[startIdx + 4] & 0xFF) << 24)
				| ((rawData[startIdx + 5] & 0xFF) << 16)
				| ((rawData[startIdx + 6] & 0xFF) << 8)
				| (rawData[startIdx + 7] & 0xFF);
	}


	/**
	 * �ѳ�����ת�����ֽ�����
	 * @param data
	 * 	������
	 * @return
	 * 	����Ϊ8�Ĵ�����볤�������ֵ������
	 */
	public static byte[] longToByte(long data) {
		byte[] res = new byte[8];
		res[0] = (byte) ((data >>> 56) & 0xFF);
		res[1] = (byte) ((data >>> 48) & 0xFF);
		res[2] = (byte) ((data >>> 40) & 0xFF);
		res[3] = (byte) ((data >>> 32) & 0xFF);
		res[4] = (byte) ((data >>> 24) & 0xFF);
		res[5] = (byte) ((data >>> 16) & 0xFF);
		res[6] = (byte) ((data >>> 8) & 0xFF);
		res[7] = (byte) (data & 0xFF);
		return res;
	}
}
